import config from '@/config'
import { Widget } from '@/models'

/** 获取选项位置边界范围 */
function getOptionRange(widget: Widget) {
  const { w: pw = Infinity, h: ph = Infinity } = widget.page || {}
  const { width, height, space } = config.checkOption

  return {
    minX: space,
    minY: space,
    maxX: pw - width - space,
    maxY: ph - height - space
  }
}

/** 统计选项坐标信息 */
function getOptionCoordinate(widget: Widget) {
  const { checkOptions } = widget
  const xs = checkOptions.map(item => item.x)
  const ys = checkOptions.map(item => item.y)

  return {
    cMinX: Math.min(...xs),
    cMinY: Math.min(...ys),
    cMaxX: Math.max(...xs),
    cMaxY: Math.max(...ys)
  }
}

/** 移动多选框控件 */
export function moveCheckGroupWidget(widget: Widget, x = 0, y = 0) {
  const { checkOptions } = widget
  const { minX, minY, maxX, maxY } = getOptionRange(widget)
  const { cMinX, cMinY, cMaxX, cMaxY } = getOptionCoordinate(widget)

  // 移动范围
  x = Math.min(maxX - cMaxX, x)
  x = Math.max(minX - cMinX, x)
  y = Math.min(maxY - cMaxY, y)
  y = Math.max(minY - cMinY, y)

  checkOptions.forEach(option => {
    x && (option.x += x)
    y && (option.y += y)
  })
}

/** 移动多选框控件选项 */
export function moveCheckGroupOption(widget: Widget, option = widget.activeOption, x = 0, y = 0) {
  if (!option) return

  const { minX, minY, maxX, maxY } = getOptionRange(widget)

  // 移动后坐标位置
  x = option.x + x
  y = option.y + y

  // 移动边界范围
  x = Math.min(maxX, x)
  x = Math.max(minX, x)
  y = Math.min(maxY, y)
  y = Math.max(minY, y)

  Object.assign(option, { x, y })
}
